package com.zwh.autoconfigure.web;


import com.zwh.common.lang.StringUtils;
import com.zwh.autoconfigure.interceptor.LogInterceptor;
import com.zwh.autoconfigure.interceptor.WebInterceptorProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

/**
 * 后台管理日志记录拦截器
 * @author monkey
 * @version 2018年1月10日
 */
@Configuration
//不能启用这个，否则springboot自动配置mvc无效 @EnableWebMvc
public class LogInterceptorConfig implements WebMvcConfigurer {

	@Autowired
	WebInterceptorProperties webInterceptorProperties;

	@ConditionalOnProperty(name="web.interceptor.log.enabled", havingValue="true", matchIfMissing=true)
	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		if(webInterceptorProperties.getLog()==null){
			return;
		}
		InterceptorRegistration registration = registry.addInterceptor(new LogInterceptor());
		List<String> addPathPatterns = webInterceptorProperties.getLog().getAddPathPatterns();
		List<String> excludePathPatterns = webInterceptorProperties.getLog().getExcludePathPatterns();
		for (String uri : addPathPatterns){
			if (StringUtils.isNotBlank(uri)){
				registration.addPathPatterns(StringUtils.trim(uri));
			}
		}
		for (String uri : excludePathPatterns){
			if (StringUtils.isNotBlank(uri)){
				registration.excludePathPatterns(StringUtils.trim(uri));
			}
		}
	}

}